﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：CacheManagerBase.cs
// 功能描述：TongTongMall
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Dependecy;
using TongTongMall.Runtime.Caching.Configuration;

namespace TongTongMall.Runtime.Caching
{
    public abstract class CacheManagerBase : ICacheManager, ISingletonDependency
    {
        /// <summary>
        /// IOC容器
        /// </summary>
        protected readonly IIocManager IocManager;

        /// <summary>
        /// 缓存配置
        /// </summary>
        protected readonly ICachingConfiguration Configuration;

        /// <summary>
        /// 缓存对象集合
        /// </summary>
        protected readonly ConcurrentDictionary<string, ICache> Caches;


        protected CacheManagerBase(IIocManager iocManager, ICachingConfiguration configuration)
        {
            IocManager = iocManager;
            Configuration = configuration;
            Caches = new ConcurrentDictionary<string, ICache>();
        }

        public IReadOnlyList<ICache> GetAllCaches()
        {
            return Caches.Values.ToImmutableList();
        }

        public virtual ICache GetCache(string name)
        {
            return Caches.GetOrAdd(name, (cacheName) =>
            {
                var cache = CreateCacheImplementation(cacheName);

                var configurators = Configuration.Configurators.Where(c => c.CacheName == null || c.CacheName == cacheName);

                foreach (var configurator in configurators)
                {
                    //执行缓存的初始化方法
                    configurator.InitAction?.Invoke(cache);
                }

                return cache;
            });
        }

        public virtual void Dispose()
        {
            foreach (var cache in Caches)
            {
                IocManager.Release(cache.Value);
            }

            Caches.Clear();
        }

        /// <summary>
        /// 创建系统对应的缓存实例
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        protected abstract ICache CreateCacheImplementation(string name);
    }
}
